package com.spic.business.informatization.meeting.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.common.collect.Lists;
import com.spic.business.informatization.meeting.domain.MeetingActivity;
import com.spic.business.informatization.meeting.domain.MeetingActivityFile;
import com.spic.business.informatization.meeting.domain.MeetingActivityGroup;
import com.spic.business.informatization.meeting.domain.MeetingActivityGroupWork;
import com.spic.business.informatization.meeting.dto.MeetingMeasureDTO;
import com.spic.business.informatization.meeting.mapper.MeetingActivityFileMapper;
import com.spic.business.informatization.meeting.mapper.MeetingActivityGroupWorkMapper;
import com.spic.business.informatization.meeting.mapper.MeetingActivityMapper;
import com.spic.business.informatization.meeting.service.IMeetingActivityService;
import com.spic.business.two.tickets.general.domain.AddSafetyPrecautionsSubtable;
import com.spic.business.two.tickets.general.domain.SafetyPrecautionsSubtable;
import com.spic.business.two.tickets.general.eum.TableCategoryEnum;
import com.spic.business.two.tickets.general.mapper.AddSafetyPrecautionsSubtableMapper;
import com.spic.business.two.tickets.general.mapper.SafetyPrecautionsSubtableMapper;
import com.spic.business.two.tickets.general.service.ITicketGeneratorService;
import com.spic.common.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;

/**
 * 工前会Service业务层处理
 * 
 * @author spic
 * @date 2021-11-04
 */
@Service
public class MeetingActivityServiceImpl implements IMeetingActivityService 
{
    @Autowired
    private MeetingActivityMapper meetingActivityMapper;
    @Autowired
    private MeetingActivityGroupWorkMapper workMapper;
    @Autowired
    private ITicketGeneratorService ticketGeneratorService;


    @Autowired
    private MeetingActivityFileMapper fileMapper;


    @Autowired
    private AddSafetyPrecautionsSubtableMapper addSafetyPrecautionsSubtableMapper;



    @Autowired
    private SafetyPrecautionsSubtableMapper safetyPrecautionsSubtableMapper;

    /**
     * 查询工前会
     * 
     * @param id 工前会主键
     * @return 工前会
     */
    @Override
    public MeetingActivity selectMeetingActivityById(Long id)
    {

        MeetingActivity result=meetingActivityMapper.selectMeetingActivityById(id);

        /** 关联附件**/
        List<MeetingActivityFile> fileList = fileMapper.selectList(
                new LambdaQueryWrapper<MeetingActivityFile>()
                        .eq(MeetingActivityFile::getMeetingActivityId, result.getId())
        );
        result.setFileList(fileList);


        /** 补充安全措施（同班前会） **/
        List<AddSafetyPrecautionsSubtable> addSafetyPrecautionsSubtableList =addSafetyPrecautionsSubtableMapper.selectList(
                new LambdaQueryWrapper<AddSafetyPrecautionsSubtable>()
                        .eq(AddSafetyPrecautionsSubtable::getParentId, result.getId().toString())
                        .eq(AddSafetyPrecautionsSubtable::getTableName, "meeting_activity")
        );
        result.setAddSafetyPrecautionsSubtableList(addSafetyPrecautionsSubtableList);


        /** 必须采取的风险措施（同班前会） **/
        List<SafetyPrecautionsSubtable> safetyPrecautionsSubtableList=safetyPrecautionsSubtableMapper.selectList(
                new LambdaQueryWrapper<SafetyPrecautionsSubtable>()
                        .eq(SafetyPrecautionsSubtable::getParentId, result.getId().toString())
                        .eq(SafetyPrecautionsSubtable::getTableName, "meeting_activity")
        );
        result.setSafetyPrecautionsSubtableList(safetyPrecautionsSubtableList);


        return result;
    }

    /**
     * 查询工前会列表
     * 
     * @param meetingActivity 工前会
     * @return 工前会
     */
    @Override
    public List<MeetingActivity> selectMeetingActivityList(MeetingActivity meetingActivity)
    {
        return meetingActivityMapper.selectMeetingActivityList(meetingActivity);
    }

    /**
     * 新增工前会
     * 
     * @param meetingActivity 工前会
     * @return 结果
     */
    @Transactional
    @Override
    public long insertMeetingActivity(MeetingActivity meetingActivity)
    {
        if(meetingActivity.getId() == null){

            meetingActivityMapper.insertMeetingActivity(meetingActivity);



            /** 补充安全措施（同班前会） **/
            List<AddSafetyPrecautionsSubtable> addSafetyPrecautionsSubtableList=meetingActivity.getAddSafetyPrecautionsSubtableList();
            if(addSafetyPrecautionsSubtableList !=null && addSafetyPrecautionsSubtableList.size()>0){
                for(AddSafetyPrecautionsSubtable item:addSafetyPrecautionsSubtableList){
                    item.setParentId(meetingActivity.getId().toString());
                    item.setTableName("meeting_activity");
                    item.setId("");
                }
            }
            addSafetyPrecautionsSubtableMapper.batchAddSafetyPrecautionsSubtable(addSafetyPrecautionsSubtableList);

            /** 必须采取的风险措施**/
            List<SafetyPrecautionsSubtable> safetyPrecautionsSubtableList=meetingActivity.getSafetyPrecautionsSubtableList();
            if(safetyPrecautionsSubtableList !=null && safetyPrecautionsSubtableList.size()>0){
                for(SafetyPrecautionsSubtable item:safetyPrecautionsSubtableList){
                    item.setParentId(meetingActivity.getId().toString());
                    item.setTableName("meeting_activity");
                    item.setId("");
                }
            }
            safetyPrecautionsSubtableMapper.batchSafetyPrecautionsSubtable(safetyPrecautionsSubtableList);

            List<MeetingActivityFile> fileList = meetingActivity.getFileList();
            if(fileList !=null && fileList.size()>0){
                for(MeetingActivityFile item:fileList){
                    item.setMeetingActivityId(meetingActivity.getId());
                    fileMapper.insert(item);
                }
            }


        }else{


            Map<String,Object> fileMap=new HashMap<>();
            fileMap.put("meeting_activity_id",meetingActivity.getId());
            /** 关联附件删除**/
            fileMapper.deleteByMap(fileMap);


            Map<String,Object> safeMap=new HashMap<>();
            safeMap.put("parent_id",meetingActivity.getId().toString());
            safeMap.put("table_name","meeting_activity");

            /** 必须采取的风险措施删除**/
            safetyPrecautionsSubtableMapper.deleteByMap(safeMap);

            /** 补充安全措施删除**/
            addSafetyPrecautionsSubtableMapper.deleteByMap(safeMap);






            /** 补充安全措施（同班前会） **/
            List<AddSafetyPrecautionsSubtable> addSafetyPrecautionsSubtableList=meetingActivity.getAddSafetyPrecautionsSubtableList();
            if(addSafetyPrecautionsSubtableList !=null && addSafetyPrecautionsSubtableList.size()>0){
                for(AddSafetyPrecautionsSubtable item:addSafetyPrecautionsSubtableList){
                    item.setParentId(meetingActivity.getId().toString());
                    item.setTableName("meeting_activity");
                }
            }
            addSafetyPrecautionsSubtableMapper.batchAddSafetyPrecautionsSubtable(addSafetyPrecautionsSubtableList);

            /** 必须采取的风险措施**/
            List<SafetyPrecautionsSubtable> safetyPrecautionsSubtableList=meetingActivity.getSafetyPrecautionsSubtableList();
            if(safetyPrecautionsSubtableList !=null && safetyPrecautionsSubtableList.size()>0){
                for(SafetyPrecautionsSubtable item:safetyPrecautionsSubtableList){
                    item.setParentId(meetingActivity.getId().toString());
                    item.setTableName("meeting_activity");
                }
            }
            safetyPrecautionsSubtableMapper.batchSafetyPrecautionsSubtable(safetyPrecautionsSubtableList);

            List<MeetingActivityFile> fileList = meetingActivity.getFileList();
            if(fileList !=null && fileList.size()>0){
                for(MeetingActivityFile item:fileList){
                    item.setMeetingActivityId(meetingActivity.getId());
                    fileMapper.insert(item);
                }
            }

            meetingActivityMapper.updateMeetingActivity(meetingActivity);
        }
        return meetingActivity.getId();
    }


    /**
     * 批量删除工前会
     * 
     * @param ids 需要删除的工前会主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteMeetingActivityByIds(Long[] ids)
    {
//        deleteWorks(ids);
//        meetingActivityMapper.deleteMeetingActivityGroupByMeetingActivityId(ids);
        return meetingActivityMapper.deleteMeetingActivityByIds(ids);
    }

    public int deleteMeetingActivityGroupByIds(Long[] ids) {
        workMapper.deleteWorksByGroupIds(Lists.newArrayList(ids));
        return meetingActivityMapper.deleteMeetingActivityGroupByIds(ids);
    }

    /**
     * 删除工前会信息
     * 
     * @param id 工前会主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteMeetingActivityById(Long id)
    {
        deleteWorks(new Long[]{id});
        meetingActivityMapper.deleteMeetingActivityGroupByMeetingActivityId(new Long[]{id});
        return meetingActivityMapper.deleteMeetingActivityById(id);
    }

    private int deleteWorks(Long[] id){
        List<MeetingActivityGroup> groups = meetingActivityMapper.selectGroupId(Stream.of(id).collect(Collectors.toList()));
        List<Long> groupIds = groups.stream().map(MeetingActivityGroup::getId).collect(Collectors.toList());
        return workMapper.deleteWorksByGroupIds(groupIds);
    }

    @Override
    public int insertMeetingActivityGroupWork(MeetingMeasureDTO measure) {
        Long groupId = measure.getGroupId();
        int delRow =workMapper.delete(new LambdaUpdateWrapper<MeetingActivityGroupWork>()
            .eq(MeetingActivityGroupWork::getMeetingActivityGroupId, groupId)
        );
        List<MeetingActivityGroupWork> groupWorks = measure.getGroupWorks();
        if(groupWorks == null) return delRow;
        for (MeetingActivityGroupWork work : groupWorks) {
            work.setMeetingActivityGroupId(groupId);
            workMapper.insert(work);
        }
        return measure.getGroupWorks().size();
    }

    @Override
    public List<MeetingActivityGroupWork> getWorkInfoByGroupId(Long id) {
       return workMapper.selectList(new LambdaQueryWrapper<MeetingActivityGroupWork>()
                .eq(MeetingActivityGroupWork::getMeetingActivityGroupId, id));
    }

    /**
     * 新增工作负责人分组信息
     * 
     * @param meetingActivity 工前会对象
     */
    private void insertMeetingActivityGroup(MeetingActivity meetingActivity)
    {
        List<MeetingActivityGroup> meetingActivityGroupList = meetingActivity.getMeetingActivityGroupList();
        Long id = meetingActivity.getId();
        if (StringUtils.isNotNull(meetingActivityGroupList))
        {
            List<MeetingActivityGroup> list = new ArrayList<MeetingActivityGroup>();
            for (MeetingActivityGroup meetingActivityGroup : meetingActivityGroupList)
            {
                meetingActivityGroup.setMeetingActivityId(id);
                list.add(meetingActivityGroup);
            }
            if (list.size() > 0)
            {
                meetingActivityMapper.batchMeetingActivityGroup(list);
            }
        }
    }

    @Override
    public Long saveGroup(MeetingActivityGroup group) {
        if (group.getId() == null) {
            meetingActivityMapper.insertMeetingActivityGroup(group);
        }else {
            meetingActivityMapper.updateActivityGroup(group);
        }
        return group.getId();
    }

    @Override
    @Transactional
    public void generateTicket(Long id) {
        MeetingActivity activity = meetingActivityMapper.selectMeetingActivityById(id);
        if(CollectionUtils.isEmpty(activity.getMeetingActivityGroupList())) return;
        List<MeetingActivityGroup> groups = activity.getMeetingActivityGroupList().stream()
                .filter(MeetingActivityGroup::needTicket).collect(toList());
        List<Long> groupsIds = groups.stream().map(MeetingActivityGroup::getId).collect(toList());
        Map<Long, List<MeetingActivityGroupWork>> workMap = workMapper.getWorks(groupsIds).stream()
                .collect(Collectors.groupingBy(MeetingActivityGroupWork::getMeetingActivityGroupId));
        compose(groups, workMap);
    }

    private void compose(List<MeetingActivityGroup> groups, Map<Long,List<MeetingActivityGroupWork>> workMap) {
        for (MeetingActivityGroup group : groups) {
            group.setGroupWorks(workMap.get(group.getId()));
            TableCategoryEnum categoryEnum = TableCategoryEnum.valueOf(group.getTicketType());
            Long id = ticketGeneratorService.createTicket(categoryEnum, group);
            group.setTicketId(id);
            meetingActivityMapper.updateActivityGroup(group);
        }
    }

}
